package com.giscloud.amp.service.auth.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSON;
import com.giscloud.amp.dao.AmpPwChgTypeMapper;
import com.giscloud.amp.dao.AmpStaffMapper;
import com.giscloud.amp.dao.AmpStaffOrgMapper;
import com.giscloud.amp.dao.AmpStaffRoleMapper;
import com.giscloud.amp.entity.*;
import com.giscloud.amp.entity.dto.AmpStaffDTO;
import com.giscloud.amp.entity.dto.PasswordDTO;
import com.giscloud.amp.entity.vo.AmpPwChgTypeVO;
import com.giscloud.amp.entity.vo.AmpStaffRoleVO;
import com.giscloud.amp.entity.vo.AmpStaffVO;
import com.giscloud.amp.service.auth.AmpStaffService;
import com.giscloud.commons.codec.DigestsUtils;
import com.giscloud.commons.model.Result;
import com.giscloud.commons.utils.PasswordUtils;
import com.giscloud.commons.utils.StringUtils;
import com.giscloud.datasource.page.PageInfo;
import com.github.pagehelper.PageHelper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

/**
 * @Author:gxd
 * @Description:
 * @Date: 11:04 2018/2/24
 * @Modified By:
 */
@SuppressWarnings("SpringJavaAutowiringInspection") //加这个注解让IDE 不报: Could not autowire
@Service("ampStaffService")
public class AmpStaffServiceImpl implements AmpStaffService {

    private final static Logger log = LoggerFactory.getLogger(AmpStaffServiceImpl.class);
    @Autowired
    private AmpStaffMapper ampStaffMapper;
    @Autowired
    private AmpStaffRoleMapper ampStaffRoleMapper;

    @Autowired
    private AmpPwChgTypeMapper ampPwChgTypeMapper;

    @Autowired
    private AmpStaffOrgMapper ampStaffOrgMapper;

//    @Autowired
//    private RedisUtils redisUtils;
    /**
     * 获取用户列表
     * @param ampStaffDTO
     * @return
     */
    @Override
    public PageInfo getAmpStaffList(AmpStaffDTO ampStaffDTO) {
        log.debug("#getAmpStaffList parameter ={}", JSON.toJSONString(ampStaffDTO));
        PageHelper.startPage(ampStaffDTO.getPage(), ampStaffDTO.getRows());
        AmpStaffExample ampStaffExample = new AmpStaffExample();
        AmpStaffExample.Criteria criteria = ampStaffExample.createCriteria();
        if(StringUtils.isNotBlank(ampStaffDTO.getLoginName())){
            criteria.andLoginNameEqualTo(ampStaffDTO.getLoginName());
        }
        if(StringUtils.isNotBlank(ampStaffDTO.getStaffName())){
            criteria.andStaffNameLike("%"+ampStaffDTO.getStaffName()+"%");
        }
        if(StringUtils.isNotBlank(ampStaffDTO.getOrgName())){
            criteria.andOrgNameLike("%"+ampStaffDTO.getOrgName()+"%");
        }
        if(StringUtils.isNotBlank(ampStaffDTO.getTelephone())){
            criteria.andTelephoneEqualTo(ampStaffDTO.getTelephone());
        }
        if(ampStaffDTO.getStaffType() != null){
            criteria.andStaffTypeEqualTo(ampStaffDTO.getStaffType());
        }
        if(ampStaffDTO.getStatusCd()!=null){
            criteria.andStatusCdEqualTo(ampStaffDTO.getStatusCd());
        }
        ampStaffExample.setOrderByClause("STAFF_ID ASC");
        //DataScope dataScope = new DataScope();
        //dataScope.setRule("in");
        //dataScope.setUserId(ampStaffDTO.getUserId());
        //dataScope.setScopeName("staff_id");
        //List<Long> list = Lists.newArrayList();
        //list.add(421L);
        //list.add(23117L);
        //list.add(23112L);
        //dataScope.setIds(list);
        //List<AmpStaffVO> ampStaffs = ampStaffMapper.selectByExample1(ampStaffExample,dataScope);
        List<AmpStaffVO> ampStaffs = ampStaffMapper.selectByExample(ampStaffExample);
        return PageInfo.of(ampStaffs);
    }

    
    /***
     * 获取相同帐户名的用户
     * @param loginName
     * @return
     */
    @Override
    public List<AmpStaffVO> getAmpStaffByStaffName(String loginName){
    	AmpStaffExample ampStaffExample = new AmpStaffExample();
        AmpStaffExample.Criteria criteria = ampStaffExample.createCriteria();
        criteria.andLoginNameEqualTo(loginName.replace("\"", ""));
    	List<AmpStaffVO> ampStaffs = ampStaffMapper.selectByExample(ampStaffExample);
    	return ampStaffs;
    }

    /**
     * 同时取账号的角色
     * @param ampStaffDTO
     * @return
     */
    @Override
    //@Cacheable(key= "'amp:getAmpStaffByCondition:'+ T(com.alibaba.fastjson.JSON).toJSONString(#ampStaffDTO)",unless="#result==null")
    public AmpStaffVO getAmpStaffByCondition(AmpStaffDTO ampStaffDTO) {
        AmpStaffVO ampStaffVO;
        List<String> list = new ArrayList<>();
        log.debug("#getAmpStaffByCondition parameter ={}", JSON.toJSONString(ampStaffDTO));
        AmpStaffExample ampStaffExample = new AmpStaffExample();
        AmpStaffExample.Criteria criteria = ampStaffExample.createCriteria();
        if(StringUtils.isNotBlank(ampStaffDTO.getLoginName())){
            criteria.andLoginNameEqualTo(ampStaffDTO.getLoginName());
        }
        if(ampStaffDTO.getStaffId() != null){
            criteria.andStaffIdEqualTo(ampStaffDTO.getStaffId());
        }
        if(ampStaffDTO.getStatusCd() != null) {
            criteria.andStatusCdEqualTo(ampStaffDTO.getStatusCd());
        }
        List<AmpStaffVO> ampStaffs = ampStaffMapper.selectByExample(ampStaffExample);
        if(!CollectionUtil.isEmpty(ampStaffs) && ampStaffs.size() == 1){
            ampStaffVO = ampStaffs.get(0);
            AmpStaffRoleExample example = new AmpStaffRoleExample();
            AmpStaffRoleExample.Criteria ampStaffRoleCriteria = example.createCriteria();
            ampStaffRoleCriteria.andStaffIdEqualTo(ampStaffVO.getStaffId());
            List<AmpStaffRoleVO> ampStaffRoleVOS = ampStaffRoleMapper.selectByExample(example);
            for (AmpStaffRoleVO ampStaffRoleVO : ampStaffRoleVOS) {
                list.add(String.valueOf(ampStaffRoleVO.getRoleId()));
            }
            //添加角色编码
            ampStaffVO.setRolesId(list);
            return ampStaffVO;
        }else{
            return  null;
        }
    }
    /**
     * 根据验证条件获取用户
     * @param ampStaffDTO
     * @return
     */
    @Override
     public AmpStaffVO getAmpStaffForValidate(AmpStaffDTO ampStaffDTO) {
        AmpStaffVO ampStaffVO;
        log.debug("#getAmpStaffForValidate parameter ={}", JSON.toJSONString(ampStaffDTO));
        AmpStaffExample ampStaffExample = new AmpStaffExample();
        AmpStaffExample.Criteria criteria = ampStaffExample.createCriteria();
        if(StringUtils.isNotBlank(ampStaffDTO.getLoginName())){
            criteria.andLoginNameEqualTo(ampStaffDTO.getLoginName());
        }
        if(StringUtils.isNotBlank(ampStaffDTO.getStaffCode())){
            criteria.andStaffCodeEqualTo(ampStaffDTO.getStaffCode());
        }
        //删除状态的也不允许同名
       // criteria.andStatusCdEqualTo(1L);
        List<AmpStaffVO> ampStaffs = ampStaffMapper.selectByExample(ampStaffExample);
        if(!CollectionUtil.isEmpty(ampStaffs) && ampStaffs.size() == 1){
            ampStaffVO = ampStaffs.get(0);
            return ampStaffVO;
        }else{
            return  null;
        }
    }

    /**
     * 添加用户
     * @param ampStaffDTO
     * @return
     */
    @Override
    @Transactional(propagation= Propagation.REQUIRED, rollbackFor=Exception.class)
    public int insert(AmpStaffDTO ampStaffDTO) {
        AmpStaff ampStaff = new AmpStaff();
        BeanUtils.copyProperties(ampStaffDTO,ampStaff);
        ampStaff.setCreatedDt(new Date());;
//        Integer pwId = ampStaff.getPwChgType();
//        AmpPwChgTypeExample ampPwChgTypeExample = new AmpPwChgTypeExample();
//        AmpPwChgTypeExample.Criteria criteria = ampPwChgTypeExample.createCriteria();
//        criteria.andPwChgTypeIdEqualTo(pwId);
//        List<AmpPwChgTypeVO> list =ampPwChgTypeMapper.selectByExample(ampPwChgTypeExample);
//        Integer times = list.get(0).getCycleTime();
//        Calendar cal = Calendar.getInstance();
//        cal.add(Calendar.DATE, times);
//        Date expDt = cal.getTime();
//        ampStaff.setExpDt(expDt);
        ampStaff.setVersion(new Date());
        ampStaff.setStaffType(1);
        ampStaff.setSaltValue(PasswordUtils.getSalt(16));
        String md5Pass = DigestsUtils.MD5Encode(DigestsUtils.MD5Encode(ampStaff.getPassword().toUpperCase()).toUpperCase()).toLowerCase();
        ampStaff.setPassword(PasswordUtils.generatePassword(md5Pass,ampStaff.getSaltValue()));
        if(ampStaffDTO.getStaffExpDt() == null){
            //不填账号到期日，默认30天
            ampStaff.setStaffExpDt( DateUtil.offsetDay(new Date(),90));
        }else{
            ampStaff.setStaffExpDt(ampStaffDTO.getStaffExpDt());
        }
        ampStaffMapper.insert(ampStaff);
        if(ampStaffDTO.getOrgId() != null){
            AmpStaffOrg ampStaffOrg = new AmpStaffOrg();
            ampStaffOrg.setStaffId(ampStaff.getStaffId());
            ampStaffOrg.setOrgId(ampStaffDTO.getOrgId());
            ampStaffOrg.setStatusCd((short)1);
            ampStaffOrgMapper.insert(ampStaffOrg);
        }
        return 1;
    }


    /**
     * 重置密码
     * @param ampStaffDTO
     * @return
     */
    @Override
    @Transactional(propagation= Propagation.REQUIRED, rollbackFor=Exception.class)
    public int resetPassword(AmpStaffDTO ampStaffDTO) {
        AmpStaffExample ampStaffExample = new AmpStaffExample();
        AmpStaffExample.Criteria criteria = ampStaffExample.createCriteria();
        if(ampStaffDTO.getStaffId() != null){
            criteria.andStaffIdEqualTo(ampStaffDTO.getStaffId());
        }

        AmpStaffExample ampStaffExample1 = new AmpStaffExample();
        AmpStaffExample.Criteria criteria1 = ampStaffExample1.createCriteria();
        if(ampStaffDTO.getStaffId() != null){
            criteria1.andStaffIdEqualTo(ampStaffDTO.getStaffId());
        }
        List<AmpStaffVO> staff = ampStaffMapper.selectByExample(ampStaffExample1);
        AmpStaff ampStaff = new AmpStaff();
        BeanUtils.copyProperties(ampStaffDTO,ampStaff);
        ampStaff.setSaltValue(PasswordUtils.getSalt(16));
        String md5Pass = DigestsUtils.MD5Encode(DigestsUtils.MD5Encode(ampStaff.getPassword().toUpperCase()).toUpperCase()).toLowerCase();
        ampStaff.setPassword(PasswordUtils.generatePassword(md5Pass,ampStaff.getSaltValue()));
        ampStaff.setVersion(new Date());
        Integer pwId = staff.get(0).getPwChgType();
        if(pwId != null && pwId !=0) {
            ampStaff.setPwChgType(staff.get(0).getPwChgType());
            AmpPwChgTypeExample ampPwChgTypeExample = new AmpPwChgTypeExample();
            AmpPwChgTypeExample.Criteria criteria2 = ampPwChgTypeExample.createCriteria();
            criteria2.andPwChgTypeIdEqualTo(pwId);
            List<AmpPwChgTypeVO> list = ampPwChgTypeMapper.selectByExample(ampPwChgTypeExample);

            Integer times = list.get(0).getCycleTime();
            Calendar cal = Calendar.getInstance();
            cal.add(Calendar.DATE, times);
            Date expDt = cal.getTime();
            ampStaff.setExpDt(expDt);
        }else{
            Calendar cal = Calendar.getInstance();
            cal.add(Calendar.DATE, 60);
            Date expDt = cal.getTime();
            ampStaff.setExpDt(expDt);
        }
        //redisUtils.del(RedisConstant.REDIS_LOGIN_COUNT + staff.get(0).getLoginName());
        return ampStaffMapper.resetPasswordByExample(ampStaff,ampStaffExample);
    }


    /**
     * 更新用户信息
     * @param ampStaffDTO
     * @return
     */
    @Override
    @Transactional(propagation= Propagation.REQUIRED, rollbackFor=Exception.class)
    public int update(AmpStaffDTO ampStaffDTO) {
        AmpStaffExample ampStaffExample = new AmpStaffExample();
        AmpStaffExample.Criteria criteria = ampStaffExample.createCriteria();
        if(ampStaffDTO.getStaffId() != null){
            criteria.andStaffIdEqualTo(ampStaffDTO.getStaffId());
        }
        AmpStaff ampStaff = new AmpStaff();
        BeanUtils.copyProperties(ampStaffDTO,ampStaff);
        ampStaff.setVersion(new Date());
        if(ampStaffDTO.getStaffExpDt() == null){
            //不填账号到期日，默认30天
            ampStaff.setStaffExpDt( DateUtil.offsetDay(new Date(),30));
        }else {
            ampStaff.setStaffExpDt(ampStaffDTO.getStaffExpDt());
        }
        if(ampStaffDTO.getOrgId() != null){
            AmpStaffOrgExample ampStaffOrgExample = new AmpStaffOrgExample();
            ampStaffOrgExample.createCriteria().andStaffIdEqualTo(ampStaff.getStaffId());
            ampStaffOrgMapper.deleteByExample(ampStaffOrgExample);
            AmpStaffOrg ampStaffOrg = new AmpStaffOrg();
            ampStaffOrg.setStaffId(ampStaff.getStaffId());
            ampStaffOrg.setOrgId(ampStaffDTO.getOrgId());
            ampStaffOrg.setStatusCd((short)1);
            ampStaffOrgMapper.insert(ampStaffOrg);
        }
        return ampStaffMapper.updateByExampleSelective(ampStaff,ampStaffExample);
       // return ampStaffMapper.updateByExample(ampStaff,ampStaffExample);
    }

    /**
     * 删除用户信息
     * @param staffId
     * @return
     */
    @Override
    @Transactional(propagation= Propagation.REQUIRED, rollbackFor=Exception.class)
    public int delete(Long staffId) {
        AmpStaffExample ampStaffExample = new AmpStaffExample();
        AmpStaffExample.Criteria criteria = ampStaffExample.createCriteria();
        if(staffId != null){
            criteria.andStaffIdEqualTo(staffId);
        }
        return ampStaffMapper.deleteByExample(ampStaffExample);
    }

    @Override
    public long countAmpStaff(AmpStaffDTO ampStaffDTO) {
        AmpStaffExample ampStaffExample = new AmpStaffExample();
        AmpStaffExample.Criteria criteria = ampStaffExample.createCriteria();
        if(ampStaffDTO.getStatusCd() != null){
            criteria.andStatusCdEqualTo(ampStaffDTO.getStatusCd());
        }
        return ampStaffMapper.countByExample(ampStaffExample);
    }

    @Override
    public long countByPhone(AmpStaffExample ampStaffExample){
        return ampStaffMapper.countByExample(ampStaffExample);
    }

    @Override
    @Transactional
    public Result changePassword(PasswordDTO passwordDTO) {
        try {
            AmpStaffExample ampStaffExample = new AmpStaffExample();
            AmpStaffExample.Criteria criteria = ampStaffExample.createCriteria();
            criteria.andStaffIdEqualTo(passwordDTO.getStaffId());
            List<AmpStaffVO> listStaff = ampStaffMapper.selectByExample(ampStaffExample);
            AmpStaffVO ampStaffVO = listStaff.get(0);
            String salt = ampStaffVO.getSaltValue();
            String md5Pass = DigestsUtils.MD5Encode(DigestsUtils.MD5Encode(passwordDTO.getOldPassword().toUpperCase()).toUpperCase()).toLowerCase();
            if(!PasswordUtils.generatePassword(md5Pass,salt).equals(ampStaffVO.getPassword())){
                return Result.error("修改失败,旧密码错误");
            } else {
                AmpStaff ampStaff = new AmpStaff();
                Integer pwId = ampStaffVO.getPwChgType();
                if(pwId != null) {
                    ampStaff.setPwChgType(ampStaffVO.getPwChgType());
                    AmpPwChgTypeExample ampPwChgTypeExample = new AmpPwChgTypeExample();
                    AmpPwChgTypeExample.Criteria criteria2 = ampPwChgTypeExample.createCriteria();
                    criteria2.andPwChgTypeIdEqualTo(pwId);
                    List<AmpPwChgTypeVO> list = ampPwChgTypeMapper.selectByExample(ampPwChgTypeExample);

                    Integer times = list.get(0).getCycleTime();
                    Calendar cal = Calendar.getInstance();
                    cal.add(Calendar.DATE, times);
                    Date expDt = cal.getTime();
                    ampStaff.setExpDt(expDt);
                }

                ampStaff.setVersion(new Date());
                md5Pass = DigestsUtils.MD5Encode(DigestsUtils.MD5Encode(passwordDTO.getNewPassword().toUpperCase()).toUpperCase()).toLowerCase();
                ampStaff.setPassword(PasswordUtils.generatePassword(md5Pass,salt));
                ampStaffMapper.updateByExampleSelective(ampStaff,ampStaffExample);
                return Result.success("修改成功");
            }
        } catch (Exception e) {
            return Result.error("修改异常");
        }
    }
}
